package com.dynamic.data.source.config.aop;

import com.dynamic.data.source.config.DataSourceAdmin;
import com.dynamic.data.source.config.DynamicDataSourceContextHolder;
import com.dynamic.data.source.domain.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 开发公司：联信
 * 版权：联信
 * <p>
 * Annotation
 *
 * @author 刘志强
 * @created Create Time: 2021/2/2
 */
@Aspect
@Component
@Slf4j
@Order(-1)
public class DynamicDataSourceAspect {
    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * 定义切点Pointcut
     */
    @Pointcut("execution(* com.dynamic.data.source.controller.*.*(..))")
    public void excudeService() {
    }

    /**
     * 环绕通知
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        log.info("----环绕通知----");

        String token = httpServletRequest.getHeader("Authorization");
        if (!StringUtils.isEmpty(token)) {
            UserInfo userInfo = DataSourceAdmin.userMap.get(token);
            log.info("当前租户Id:{}", userInfo.toString());
            DynamicDataSourceContextHolder.setDataSourceKey(String.valueOf(userInfo.getTenantId()));
            Object result = pjp.proceed();
            DynamicDataSourceContextHolder.clearDataSourceKey();
            return result;
        } else {
            DynamicDataSourceContextHolder.setDataSourceKey("default");
            Object result = pjp.proceed();
            DynamicDataSourceContextHolder.clearDataSourceKey();
            return result;
        }
    }

}
